#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, re
from munkres import Munkres, print_matrix
import time
from datetime import date
from sheepomatic import Sheep,Shepherd
import sheepomatic

# READING INFORMATION FROM CSV FILES

class Csv_file:
   """Methods for handling semicolon-separated csv files"""
   @classmethod
   def csvline2list(cls,csvline):
      """converts a semicolon-separated line into a list"""
      list = []
      for listitem in re.split(";",csvline):
         if re.match(r"\".*\"",listitem):
            list.append( listitem.strip("\"") )
         else:
            list.append(listitem)
      return list
   
   @classmethod
   def read_sheep_file(cls,filename):
      """returns a list of sheep obtained from the given file"""
      f = open(filename, 'r')
      sheep_list = []
      #
      firstline = f.readline().strip()
      attrlist = Csv_file.csvline2list(firstline)
      #
      for line in f.readlines():
         line = line.strip()
         if not re.match(r"^\s*$",line):
            newsheep = Sheep(attrlist,Csv_file.csvline2list(line))
            sheep_list.append(newsheep)
      f.close()
      return sheep_list
   
   @classmethod
   def read_shepherd_file(cls,filename):
      """returns a list of shepherds obtained from the given file"""
      f = open(filename, 'r')
      shepherd_list = []
      #
      firstline = f.readline().strip()
      attrlist = Csv_file.csvline2list(firstline)
      #
      for line in f.readlines():
         line = line.strip()
         if not re.match(r"^\s*$",line):
            newshepherd = Shepherd(attrlist,Csv_file.csvline2list(line))
            shepherd_list.append(newshepherd)
      f.close()
      return shepherd_list
   
   @classmethod
   def read_and_interpret_sheep_file(cls,filename,conf_filename):
      """reads and interprets sheep"""
      sheep_list = Csv_file.read_sheep_file(filename)
      sheepomatic.interpret_attrs(sheep_list, conf_filename)
      return sheep_list
   
   @classmethod
   def read_and_interpret_shepherd_file(cls,filename,conf_filename):
      """reads and interprets shepherds"""
      shepherd_list = Csv_file.read_shepherd_file(filename)
      sheepomatic.interpret_attrs(shepherd_list, conf_filename)
      return shepherd_list

class Sheep_brief_file:
   """methods for handling sheep brief files"""
   @classmethod
   def read_sheep_brief_file(cls,filename):
      """reads interpreted data directly from the given file"""
      f = open(filename, 'r')
      sheep_list = []
      i=0
      #
      for line in f.readlines():
         i=i+1
         line = line.strip()
         value_list = line.split("\t")
         if len(value_list) == 6:
            sheep_list.append(Sheep.from_tuple(tuple(value_list)))
         else:
            print >> sys.stderr,"Error reading file "+filename+". Can't interpret line "+str(i)+ " only " + str(len(value_list)) + " values"
      f.close()
      return sheep_list
   
   @classmethod
   def write_sheep_brief_file(cls,sheep_list):
      """writes interpreted data directly into a file"""
      for sheep in sheep_list:
         print sheep.mail+"\t"+\
               ",".join(sheep.langs)+"\t"+\
               sheep.country+"\t"+\
               sheepomatic.interpreted_date_as_str(sheep.arrival_date)+"\t"+\
               sheep.faculty+"\t"+\
               sheep.gender

class Shepherd_brief_file:
   """methods for handling shepherd brief files"""
   @classmethod
   def read_shepherd_brief_file(cls,filename):
      """reads interpreted data directly from the given file"""
      f = open(filename, 'r')
      shepherd_list = []
      i=0
      #
      for line in f.readlines():
         i=i+1
         line = line.strip()
         value_list = line.split("\t")
         if len(value_list) == 7:
            shepherd_list.append(Shepherd.from_tuple(tuple(value_list)))
         else:
            print >> sys.stderr,"Error reading file "+filename+". Can't interpret line "+str(i)+ " only " + str(len(value_list)) + " values"
      f.close()
      return shepherd_list

   @classmethod
   def write_shepherd_brief_file(cls,shepherd_list):
      """writes interpreted data directly into a file"""
      for shepherd in shepherd_list:
         print shepherd.mail+"\t"+\
               ",".join(shepherd.langs)+"\t"+\
               ",".join(shepherd.country_prefs)+"\t"+\
               sheepomatic.interpreted_date_as_str(shepherd.ava_date)+"\t"+\
               shepherd.faculty+"\t"+\
               shepherd.gender+"\t"+\
               str(shepherd.capacity)

class Brief_file_replacer:
   @classmethod
   def replace_value(cls,filename,index,pattern,replacement):
      """Replaces value occurrences in the given brief file

      Parameters:
      filename -- the name of the brief file
      index -- the index of the column/attribute (counting from 1) to replace in
      pattern -- the string to replace
      replacement -- the string to replace the pattern with
      """
      f = open(filename, 'r')
      index = int(index)
      value_list = []
      i=0
      #
      for line in f.readlines():
         i=i+1
         line = line.strip()
         value_list = line.split("\t")
         print >>sys.stderr, value_list, pattern, value_list[index-1]
         if len(value_list) >= index:
            if value_list[index-1] == pattern:
               value_list[index-1] = replacement
               print >> sys.stderr, "Replacing",pattern,"with",replacement
         print "\t".join(value_list)
      f.close()
